package com.temp.controller.user;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.temp.dto.WithdrawDTO;
import com.temp.entity.User;
import com.temp.entity.Withdraw;
import com.temp.exception.BaseException;
import com.temp.result.Result;
import com.temp.service.CampaignService;
import com.temp.service.UserService;
import com.temp.service.WithdrawService;
import com.temp.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/withdraw")
@Api(tags = "用户提现接口")
@Slf4j
@Validated
public class WithdrawController {

    @Autowired
    private WithdrawService withdrawService;

    @Autowired
    private UserService userService;

    @Autowired
    private CampaignService campaignService;

    @PostMapping("/add")
    @ApiOperation("添加提现记录")
    @RequiresPermissions("user:withdraw:add")
    public Result addWithdraw(@Valid @RequestBody WithdrawDTO withdrawDTO) {
        User user = ShiroUtils.getUser();
        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getId, user.getId()));
        if(one == null) {
            throw new BaseException("apiMsg.notExistUser");
        }
        if(withdrawDTO.getAmount().compareTo(one.getBalance()) > 0) {
            throw new BaseException("apiMsg.withdrawAmount");
        }
        Integer allNotEndedCampaign = campaignService.findAllNotEndedCampaign(user.getId());
        if(allNotEndedCampaign > 0) {
            throw new BaseException("apiMsg.notEndedCampaign");
        }
        Withdraw withdraw = new Withdraw();
        BeanUtils.copyProperties(withdrawDTO, withdraw);
        withdraw.setUserId(user.getId());
        boolean isSuccess = withdrawService.save(withdraw);
        return isSuccess ? Result.success("apiMsg.optionSuccess") : Result.error("apiMsg.optionError");
    }

    @GetMapping("/query")
    @ApiOperation("查询提现中状态")
    @RequiresPermissions("user:withdraw:query")
    public Result getWithdrawStatus() {
        User user = ShiroUtils.getUser();
        Withdraw one = withdrawService.getOne(Wrappers.<Withdraw>lambdaQuery()
                .eq(Withdraw::getUserId, user.getId())
                .eq(Withdraw::getStatus, 0));
        return one == null ? Result.success(null,"apiMsg.querySuccess") : Result.success(one,"apiMsg.queryError");
    }
}
